package com.example.forest.interceptor;

import com.dtflys.forest.http.ForestRequest;
import com.dtflys.forest.interceptor.Interceptor;
import com.example.forest.util.SignUtils;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

public class TqInterceptor implements Interceptor {

    public static final String APP_KEY= "8FB345B8693CCD008E7F3D342FDAFE8E6574BC1ECEB825E0";
    public static final String APP_SECRET="86f9e34b781f40439ddd982fb9a2ab18";
    @Override
    public boolean beforeExecute(ForestRequest request) {

        Map<String, Object> paramMap = request.body().nameValuesMap();
        paramMap.put("app_key", APP_KEY);
        paramMap.put("v", "0.9");
        paramMap.put("timestamp", getCurrentDate());
        paramMap.put("sign_method", "md5");
        paramMap.put("format", "json");

        // 计算签名
        String sign = "";
        try {
            sign = SignUtils.signTopRequest(paramMap, APP_SECRET, "md5");
            paramMap.put("sign", sign);
        } catch (IOException e) {
            System.err.println(e);
        }
        request.addBody("app_key", APP_KEY);
        request.addBody("v", "0.9");
        request.addBody("timestamp", getCurrentDate());
        request.addBody("sign_method", "md5");
        request.addBody("format", "json");
        request.addBody("sign", sign);
        return true;  // 继续执行请求返回true
    }

    public static String getCurrentDate() {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String result = formatter.format(new Date());
        return result;
    }
}
